/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.compiler.support;

import com.aduib.boot.common.compiler.AbstractCompiler;
import com.aduib.boot.common.compiler.JavaPattern;
import com.aduib.boot.common.util.ClassUtils;
import com.aduib.boot.common.util.IOUtils;
import com.aduib.boot.common.util.StrUtils;
import javassist.CtClass;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.regex.Matcher;

/**
 * @description: JavassistClassBuilder
 * @author: zzh
 * @date: 2021/10/15 15:57
 */
public class JavassistCompiler extends AbstractCompiler {

  private final boolean enabledPrintClassInfo =
      Boolean.parseBoolean(System.getProperty("aduib.class.enabledPrint", "false"));

  @Override
  public Class<?> doCompile(String name, String source) throws Throwable {
    JavassistClassBuilder builder = new JavassistClassBuilder();
    builder.setClassName(name);

    Matcher matcher = JavaPattern.IMPORT_PATTERN.matcher(source);
    while (matcher.find()) {
      builder.addImports(matcher.group(1).trim());
    }

    matcher = JavaPattern.EXTENDS_PATTERN.matcher(source);
    if (matcher.find()) {
      builder.setSuperClassName(matcher.group(1).trim());
    }

    matcher = JavaPattern.IMPLEMENTS_PATTERN.matcher(source);
    if (matcher.find()) {
      String[] ifaces = matcher.group(1).trim().split("\\,");
      Arrays.stream(ifaces).forEach(i -> builder.addInterface(i.trim()));
    }

    String body = source.substring(source.indexOf('{') + 1, source.length() - 1);
    body = body.replaceAll("\\n", "");
    String[] methods = JavaPattern.METHODS_PATTERN.split(body);
    String className = ClassUtils.getSimpleClassName(name);
    Arrays.stream(methods)
        .map(String::trim)
        .filter(m -> !m.isEmpty())
        .forEach(
            method -> {
              if (method.startsWith(className)) {
                builder.addConstructor("public " + method);
              } else if (JavaPattern.FIELD_PATTERN.matcher(method).matches()) {
                builder.addField("private " + method);
              } else {
                builder.addMethod("public " + method);
              }
            });

    ClassLoader classLoader = ClassUtils.getDefaultClassLoader(JavassistCompiler.class);
    CtClass cls = builder.build(classLoader);
    if (enabledPrintClassInfo) {
      cls.debugWriteFile(
          System.getProperty("user.home")
              + File.separator
              + className
              + JavaPattern.CLASS_EXTENSION);
    }
    return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain());
  }

  @Override
  protected Class<?> doCompile(byte[] code, String source) throws Throwable {
    return doCompile(StrUtils.str(code, StandardCharsets.UTF_8), source);
  }

  @Override
  protected Class<?> doCompile(InputStream inputStream, String source) throws Throwable {
    return doCompile(IOUtils.readBytes(inputStream), source);
  }
}
